package com.ly.lypopupwindowdemo.decoration;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by liying on 2017/9/11.
 *
 * Decoratoin学习！
 * http://blog.csdn.net/briblue/article/details/70161917
 */

public class ColorDivederDecoration extends RecyclerView.ItemDecoration {

    private float mDividerHeight;
    private Paint mPaint;

    public ColorDivederDecoration() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        //第一个ItemView不需要在上面绘制分割线
        if (parent.getChildAdapterPosition(view)!=0){
            //这里直接硬编码1px
            outRect.top=1;
            mDividerHeight=5;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);

        int childCount = parent.getChildCount();
        for (int i =0;i<childCount;i++){
            View view = parent.getChildAt(i);
            int index = parent.getChildAdapterPosition(view);

            //第一个item不需要绘制
            if (index==0){
                continue;
            }
            /**
             * 分割线是一个矩形，即使它的高度只有1px
             * 绘制这个矩形我们需要知道他的左上右下的坐标
             * 这里解释一下dividerTop的计算由来
             * 分割线的高度=bottom-top
             * 所以，top  = bottom-mDividerHeight
             * 所以，dividerTop = view.getTop=mDividerHeight
             */
            float dividerTop = view.getTop()-mDividerHeight;
            float dividerLeft = parent.getPaddingLeft();
            float dividerBottom = view.getTop();
            float dividerRight = parent.getWidth()-parent.getPaddingRight();

            c.drawRect(dividerLeft,dividerTop,dividerRight,dividerBottom,mPaint);
        }

    }
}
